﻿using System.Threading.Tasks;
using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Windows.Media.Control;

namespace SpotCtl
{
    public partial class MainWindow : Window
    {
        private GlobalSystemMediaTransportControlsSession _mediaSession;
        private readonly DispatcherTimer _statusTimer;

        public MainWindow()
        {
            InitializeComponent();
            _statusTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1)
            };
            _statusTimer.Tick += StatusTimer_Tick;
            Loaded += MainWindow_Loaded;
        }

        private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            await InitializeMediaSession();
            _statusTimer.Start();
        }

        private async Task InitializeMediaSession()
        {
            var sessionManager = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync();
            _mediaSession = sessionManager.GetCurrentSession();

            if (_mediaSession != null)
            {
                _mediaSession.MediaPropertiesChanged += async (s, args) =>
                    await UpdatePlaybackStatus();
            }
        }

        private async void StatusTimer_Tick(object sender, EventArgs e)
        {
            await UpdatePlaybackStatus();
        }

        private async Task UpdatePlaybackStatus()
        {
            if (_mediaSession == null) return;

            var playbackInfo = _mediaSession.GetPlaybackInfo();
            await Dispatcher.InvokeAsync(() =>
            {
                var isPlaying = playbackInfo?.PlaybackStatus ==
                    GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing;

                // 切换播放/暂停图标
                PlayPauseIcon.Data = isPlaying
                    ? (Geometry)FindResource("PauseIcon")
                    : (Geometry)FindResource("PlayIcon");
            });
        }

        private async void PlayPause_Click(object sender, RoutedEventArgs e)
        {
            if (_mediaSession != null)
                await _mediaSession.TryTogglePlayPauseAsync();
        }

        private void GetMediaInfo()
        {
            if (_mediaSession != null)
            {
                var mediaInfo =  _mediaSession.TryGetMediaPropertiesAsync();
                if (mediaInfo != null)
                {
                   mediaInfo.GetAwaiter().OnCompleted(() =>
                    {
                        var media = mediaInfo.GetResults();
                        if (media != null)
                        {
                            var mediaInfo = $"{media.AlbumTitle} {media.AlbumArtist}";
                            TrackText.Text = mediaInfo;
                        }
                    });
                }
            }
        }

        private async void Next_Click(object sender, RoutedEventArgs e)
        {
            if (_mediaSession != null)
                await _mediaSession.TrySkipNextAsync();
            
        }


        private async void Prev_Click(object sender, RoutedEventArgs e)
        {
            if (_mediaSession != null)
                await _mediaSession.TrySkipPreviousAsync();
        }

        private void Window_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                DragMove();
        }

        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            _statusTimer.Stop();
            base.OnClosing(e);
        }
    }
}